package com.boat.io.util;

import org.apache.commons.io.*;
import sun.net.www.protocol.http.HttpURLConnection;

import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import static java.lang.System.out;

/**
 * 文件工具类
 *
 * @author panda fang
 * @version 1.0
 * @date 2017-08-26
 */
public class DownLoad {

    public static void main(String[] args) throws IOException {
        String url = "https://www.okfree.men/filestores/2021/04/28//182533601e34991612b96dd82e898459.mp3";
        downLoadFromUrl(url,"《邪神 03》NJ：流景","E:\\");

//        get(url,"F:\\asmr\\","123.mp3");

    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){

            fos.close();

        }
        if(inputStream!=null){
            inputStream.close();

        }
        System.out.println("info:"+url+" download success");
    }


    public static void get(String url,String saveDir,String fileName)  {
        HttpURLConnection urlConn = null;
        InputStream ins = null;
        try{
            long startTime = System.currentTimeMillis();
            URL imgURL = new URL(url.trim());//转换URL
             urlConn = (HttpURLConnection) imgURL.openConnection();//构造连接
            urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36");
            urlConn.setConnectTimeout(30000000);
            urlConn.setReadTimeout(30000000);
            urlConn.connect();
            if (urlConn.getResponseCode() == 200) {//返回的状态码是200 表示成功
                ins = urlConn.getInputStream(); //获取输入流,从网站读取数据到 内存中
                FileUtils.copyInputStreamToFile(ins, new File(saveDir, fileName));

            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            urlConn.disconnect();
            try {
                ins.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

        /**
         * 使用传统io stream 下载文件
         *
         * @param url
         * @param saveDir
         * @param fileName
         */
        public static void download (String url, String saveDir, String fileName){

            BufferedOutputStream bos = null;
            InputStream is = null;
            try {
                byte[] buff = new byte[8192];
                is = new URL(url).openStream();
                File file = new File(saveDir, fileName);
                file.getParentFile().mkdirs();
                bos = new BufferedOutputStream(new FileOutputStream(file));
                int count = 0;
                while ((count = is.read(buff)) != -1) {
                    bos.write(buff, 0, count);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }

        /**
         * 利用 commonio 库下载文件，依赖Apache Common IO ，官网 https://commons.apache.org/proper/commons-io/
         *
         * @param url
         * @param saveDir
         * @param fileName
         */
        public static void downloadByApacheCommonIO (String url, String saveDir, String fileName){
            try {
                URL l = new URL(url);

                FileUtils.copyURLToFile(l, new File(saveDir, fileName));

            } catch (IOException e) {
                out.println(e.getMessage() + " 下载失败：" + url + " " + fileName);
                e.printStackTrace();
            }
        }

        /**
         * 使用NIO下载文件， 需要 jdk 1.4+
         *
         * @param url
         * @param saveDir
         * @param fileName
         */
        public static void downloadByNIO (String url, String saveDir, String fileName){
            ReadableByteChannel rbc = null;
            FileOutputStream fos = null;
            FileChannel foutc = null;
            try {
                rbc = Channels.newChannel(new URL(url).openStream());
                File file = new File(saveDir, fileName);
                file.getParentFile().mkdirs();
                fos = new FileOutputStream(file);
                foutc = fos.getChannel();
                foutc.transferFrom(rbc, 0, Long.MAX_VALUE);

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (rbc != null) {
                    try {
                        rbc.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (foutc != null) {
                    try {
                        foutc.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        /**
         * 使用NIO下载文件， 需要 jdk 1.7+
         *
         * @param url
         * @param saveDir
         * @param fileName
         */
        public static void downloadByNIO2 (String url, String saveDir, String fileName){
            try (InputStream ins = new URL(url).openStream()) {
                Path target = Paths.get(saveDir, fileName);
                Files.createDirectories(target.getParent());
                Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING);

            } catch (IOException e) {
                out.println(e.getMessage() + " 下载失败：" + url + " " + fileName);
//            e.printStackTrace();
            }

        }
    }